package DAOS;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import Hibernate.HibernateUtil;
import Negocio.Agenda;
import Negocio.Medico;
import Negocio.Horario;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;


public class AgendaDAO {
	
private static AgendaDAO instancia = null;
	
	private static SessionFactory sf = null;

	public static AgendaDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new AgendaDAO();
		} 
		return instancia;
	}

	
	
	public void guardarAgenda(Agenda a){

		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(a);
		session.flush();
		session.getTransaction().commit();
		session.close();
		
	}
	
	public void modificarAgenda(Agenda a){
		
		Session session = sf.openSession();
		session.beginTransaction();
		session.update(a);
		session.flush();
		session.getTransaction().commit();
		session.close();

	}
	

	public Agenda cargarAgenda (Medico m){
		Agenda a = new Agenda();
		
		Session session = sf.openSession();
		
		Query q = session.createQuery(
					"SELECT" +
					"FROM Agenda g JOIN Medico me" +
					"WHERE me.idMedico = " + m.getIdMedico()
		);
		a.setIdAgenda(q.executeUpdate());
		
		Query q1 = session.createQuery(
					"SELECT w.inicio, w.fin, w.dia" +
					"(SELECT g.idAgenda, h.inicio, h.fin, h.dia" +
					"FROM Agenda g JOIN Horario h  ON g.idAgenda = h.idAgenda)w JOIN Medico ON me g.idAgenda = me.idAgenda anda" +
					"WHERE me.idMedico = " + m.getIdMedico()
		);
		List <Horario> horarios = new ArrayList (q1.list());
		Horario[] h = new Horario[7];
		
		for (int i=0 ; i<horarios.size() ; i++){
			h[i].setDia(horarios.get(i).getDia());
			h[i].setFin(horarios.get(i).getFin());
			h[i].setInicio(horarios.get(i).getInicio());
		}
		
		a.setDiasAtencion(h);
		
		session.close();
		return a;
	}
}
